package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.R;
import com.secneo.appshare.adapter.RecomAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.AppRecom;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.RecomThread;

public class MainAppsActivity extends CommonActivity {
	public static boolean mRecyleFlag = false;
	private ProgressDialog mProgressDialog = null;
	private RecomThread mAppsThread = null;
	// private GridView mAppsGridView = null;
	private RecomAdapter mAppAdapter0 = null;
	private RecomAdapter mAppAdapter1 = null;
	private RecomAdapter mAppAdapter2 = null;

	private ViewPager mPager;// 页卡内容
	private List<View> listViews; // Tab页面列表
	private ImageView cursor;// 动画图片
	private TextView t1, t2, t3;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.MSG_GET_RECOMS_NETWORK_ERROR:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
					mProgressDialog = null;
				}
				View view = findViewById(R.id.view_network_error);
				view.setVisibility(View.VISIBLE);
				break;

			case Constants.MSG_GET_RECOMS_FINISH:
				int curIndex = msg.arg1;
				if (curIndex == 0) {
					showRecomAppGridView0(mAppsThread.getAppList());
				} else if (curIndex == 1) {
					showRecomAppGridView1(mAppsThread.getAppList());
				} else if (curIndex == 2) {
					showRecomAppGridView2(mAppsThread.getAppList());
				}
				break;

			case Constants.MSG_GET_APPICON_FINISH:
				curIndex = msg.arg1;
				if (curIndex == 0) {
					mAppAdapter0.notifyDataSetChanged();
				} else if (curIndex == 1) {
					mAppAdapter1.notifyDataSetChanged();
				} else if (curIndex == 2) {
					mAppAdapter2.notifyDataSetChanged();
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_apps);
		setContext(this);
		// mAppsGridView = (GridView) findViewById(R.id.app_grid);
		// mAppsGridView.setNumColumns(2);
		// mAppsGridView.setOnItemClickListener(new
		// AppGridViewItemClickListener());
		// mAppsGridView.setOnScrollListener(mScrollListner);
		InitPageViewTitleTextView();
		InitCursorImageView();
		InitViewPager();
//		startProgressDialog();
		mPager.setCurrentItem(1);
		// mAppsThread = new RecomThread(MainAppsActivity.this, mHandler,
		// Constants.RECOM_APP_IS_GAMEONLY, "", mPageNum0);
		// mAppsThread.start();
	}

	/**
	 * 初始化头标
	 */
	private void InitPageViewTitleTextView() {
		t1 = (TextView) findViewById(R.id.text1);
		t2 = (TextView) findViewById(R.id.text2);
		t3 = (TextView) findViewById(R.id.text3);

		t1.setOnClickListener(new PageViewTitleTextOnClickListener(0));
		t2.setOnClickListener(new PageViewTitleTextOnClickListener(1));
		t3.setOnClickListener(new PageViewTitleTextOnClickListener(2));
	}

	/**
	 * 头标点击监听
	 */
	public class PageViewTitleTextOnClickListener implements
			View.OnClickListener {
		private int index = 0;

		public PageViewTitleTextOnClickListener(int i) {
			index = i;
		}

		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 初始化ViewPager
	 */
	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		LayoutInflater mInflater = getLayoutInflater();
		listViews.add(mInflater.inflate(R.layout.appshare_apps_gridview, null));
		listViews.add(mInflater.inflate(R.layout.appshare_apps_gridview, null));
		listViews.add(mInflater.inflate(R.layout.appshare_apps_listview, null));
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				if (mItemSum0 == 0) {
					startProgressDialog();
					mAppsThread = new RecomThread(MainAppsActivity.this,
							mHandler, Constants.RECOM_APP_IS_GAMEONLY, "",
							mPageNum0,arg0);
					mAppsThread.start();
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				if (mItemSum1 == 0) {
					startProgressDialog();
					mAppsThread = new RecomThread(MainAppsActivity.this,
							mHandler, Constants.RECOM_APP_IS_GAMEONLY, "",
							mPageNum1,arg0);
					mAppsThread.start();
				}
				break;
			case 2:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				if (mItemSum2 == 0) {
					startProgressDialog();
					mAppsThread = new RecomThread(MainAppsActivity.this,
							mHandler, Constants.RECOM_APP_IS_GAMEONLY, "",
							mPageNum2,arg0);
					mAppsThread.start();
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageScrollStateChanged(int arg0) {
		}
	}

	/**
	 * 初始化动画
	 */
	private void InitCursorImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		// bmpW = BitmapFactory.decodeResource(getResources(),
		// R.drawable.apps_pageview_cursor)
		// .getWidth();// 获取图片宽度
		bmpW = screenW / 3;
		// keep here ,just for we will use cursor ion further.
		offset = (screenW / 3 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {

			if (arg1 < 3) {
				((ViewPager) arg0).addView(mListViews.get(arg1 % 3), 0);
			}
			// 测试页卡1内的按钮事件
			if (arg1 == 0) {
				GridView appGridView = (GridView) mListViews.get(arg1)
						.findViewById(R.id.app_grid);
				appGridView.setNumColumns(2);
				appGridView
						.setOnItemClickListener(new AppViewItemClickListener());
				appGridView.setOnScrollListener(mScrollListner0);
				if(mAppAdapter0 == null)
					mAppAdapter0 = new RecomAdapter(MainAppsActivity.this, new ArrayList<AppRecom>());
				appGridView.setAdapter(mAppAdapter0);
			}
			if (arg1 == 1) {
				GridView appGridView = (GridView) mListViews.get(arg1)
						.findViewById(R.id.app_grid);
				appGridView.setNumColumns(2);
				appGridView
						.setOnItemClickListener(new AppViewItemClickListener());
				appGridView.setOnScrollListener(mScrollListner1);
				if(mAppAdapter1 == null)
					mAppAdapter1 = new RecomAdapter(MainAppsActivity.this, new ArrayList<AppRecom>());
				appGridView.setAdapter(mAppAdapter1);
			}
			if (arg1 == 2) {
				ListView appListView = (ListView) mListViews.get(arg1)
						.findViewById(R.id.app_list);
				appListView
						.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								Intent intent = new Intent();
								intent.setClass(MainAppsActivity.this, MainAppDetailActivity.class);
								startActivity(intent);
							}
						});
				appListView.setOnScrollListener(mScrollListner2);
				if(mAppAdapter2 == null)
					mAppAdapter2 = new RecomAdapter(MainAppsActivity.this, new ArrayList<AppRecom>());
				appListView.setAdapter(mAppAdapter2);
			}
			return mListViews.get(arg1 % 3);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	@Override
	protected void onPause() {
		if (mRecyleFlag) {
			// 回收资源
			mRecyleFlag = false;
			endChildrenThreads();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// mAppsGridView.setAdapter(null);
		if (mAppAdapter0 != null)
			mAppAdapter0.freeDrawable();
		if (mAppAdapter1 != null)
			mAppAdapter1.freeDrawable();
		if (mAppAdapter2 != null)
			mAppAdapter2.freeDrawable();
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Boolean needInit = intent.getBooleanExtra("FromGroup", false);
		if (needInit) {
			// 重新获取资源
			startProgressDialog();
			endChildrenThreads();
//			mAllowGetLogAgain = false;
//			mAppsThread = new RecomThread(MainAppsActivity.this, mHandler,
//					Constants.RECOM_APP_IS_GAMEONLY, "", mPageNum0,currIndex);
//			mAppsThread.start();
		}
		super.onNewIntent(intent);
	}

	private void startProgressDialog() {
		View view = findViewById(R.id.view_network_error);
		view.setVisibility(View.GONE);
		// mAppsGridView.setVisibility(View.GONE);
		if (mProgressDialog != null)
			mProgressDialog.dismiss();
		mProgressDialog = new ProgressDialog(MainAppsActivity.this);
		mProgressDialog.setMessage("加载中，请稍候...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}

	private void endChildrenThreads() {
		if (mAppsThread != null) {
			mAppsThread.stopThread();
			mAppsThread = null;
		}

		// mAppsGridView.setAdapter(null);
		// if (mAppAdapter != null)
		// mAppAdapter.freeDrawable();

		// mAllowGetLogAgain = true;
		// mPageNum = 1;
		// mItemSum = 0;
	}

	public void showRecomAppGridView0(List<AppRecom> list) {
		if (list == null) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			return;
		}
		// mAppsGridView.setVisibility(View.VISIBLE);
		
			mAppAdapter0.appandAdapter(list);
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			mAppAdapter0.notifyDataSetChanged();
			mItemSum0 = mAppAdapter0.getCount();
			// int test40 = mItemSum % 40;
			// if (test40 == 0)
			// mAppsGridView.setSelection(mItemSum - 40);
			// else
			// mAppsGridView.setSelection(mItemSum - test40);

	}

	public void showRecomAppGridView1(List<AppRecom> list) {
		if (list == null) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			return;
		}
		
			mAppAdapter1.appandAdapter(list);
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			mAppAdapter1.notifyDataSetChanged();
			mItemSum1 = mAppAdapter1.getCount();
			// int test40 = mItemSum % 40;
			// if (test40 == 0)
			// mAppsGridView.setSelection(mItemSum - 40);
			// else
			// mAppsGridView.setSelection(mItemSum - test40);

	}

	public void showRecomAppGridView2(List<AppRecom> list) {
		if (list == null) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			return;
		}
		// mAppsGridView.setVisibility(View.VISIBLE);
		
			mAppAdapter2.appandAdapter(list);
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
			mAppAdapter2.notifyDataSetChanged();
			mItemSum2 = mAppAdapter2.getCount();
			// int test40 = mItemSum % 40;
			// if (test40 == 0)
			// mAppsGridView.setSelection(mItemSum - 40);
			// else
			// mAppsGridView.setSelection(mItemSum - test40);

	}

	class AppViewItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			try {
				Intent intent = new Intent();
				intent.setClass(MainAppsActivity.this,
						ApplicationActivity.class);
				RecomAdapter mAppAdapter = null;
				if (currIndex == 0)
					mAppAdapter = mAppAdapter0;
				else if (currIndex == 1)
					mAppAdapter = mAppAdapter1;
				else if (currIndex == 2)
					mAppAdapter = mAppAdapter2;
				AppRecom app_recom = (AppRecom) mAppAdapter.getItem(position);
				Bundle mBundle = new Bundle();
				mBundle.putString("package_name", app_recom.package_name);
				mBundle.putInt("n", 20);
				String uid = LocalStore.getLocaleStoreInstance(
						MainAppsActivity.this).getUid();
				mBundle.putString("uid", uid);
				mBundle.putBoolean("installed_not_addicted", true);

				PackageManager manager = MainAppsActivity.this
						.getPackageManager();
				try {
					PackageInfo info = manager.getPackageInfo(
							app_recom.package_name, 0);
					if (info != null)
						mBundle.putBoolean("user_app_flag", true);
					else
						mBundle.putBoolean("user_app_flag", false);

				} catch (Exception e) {
					mBundle.putBoolean("user_app_flag", false);
				}

				/* Send the icon */
				mBundle.putString("app_icon", app_recom.app_icon);
				if (app_recom.app_icon_drawable != null) {
					try {
						Bitmap bitmap = ((BitmapDrawable) app_recom.app_icon_drawable)
								.getBitmap();
						ByteArrayOutputStream stream = new ByteArrayOutputStream();

						bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
						byte[] bitmapdata = stream.toByteArray();
						mBundle.putByteArray("app_icon_array", bitmapdata);
					} catch (Exception ex) {
						ex.printStackTrace();
						mBundle.putByteArray("app_icon_array", null);
					}

				} else {
					mBundle.putByteArray("app_icon_array", null);
				}
				mBundle.putString("app_name", app_recom.app_name);

				intent.putExtras(mBundle);
				startActivity(intent);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return;
		}
	}

	// 以下为分页显示代码
	private static boolean mAllowGetLogAgain0 = false;
	private static boolean mAllowGetLogAgain1 = false;
	private static boolean mAllowGetLogAgain2 = false;
	private static int mItemSum0 = 0;
	private static int mItemSum1 = 0;
	private static int mItemSum2 = 0;
	private int mPageNum0 = 1;
	private int mPageNum1 = 1;
	private int mPageNum2 = 1;

	public static void setAllowGetPageAgain(int curIndex) {
		if(curIndex == 0){
			int test40 = mItemSum0 % 40;
			if ((test40 != 0) || (mItemSum0 >= 200))
				mAllowGetLogAgain0 = false;
			else
				mAllowGetLogAgain0 = true;
		}else if(curIndex == 1){
			int test40 = mItemSum1 % 40;
			if ((test40 != 0) || (mItemSum1 >= 200))
				mAllowGetLogAgain1 = false;
			else
				mAllowGetLogAgain1 = true;
		}else if(curIndex == 2){
			int test40 = mItemSum2 % 40;
			if ((test40 != 0) || (mItemSum2 >= 200))
				mAllowGetLogAgain2 = false;
			else
				mAllowGetLogAgain2 = true;
		}	
	}

	private OnScrollListener mScrollListner0 = new OnScrollListener() {
		private int lastItem = 0;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (mAppAdapter0 != null && lastItem == mAppAdapter0.getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (!mAllowGetLogAgain0)
					return;
				mAllowGetLogAgain0 = false;
				mPageNum0++;

				mProgressDialog = new ProgressDialog(MainAppsActivity.this);
				mProgressDialog.setMessage("加载中，请稍候...");
				mProgressDialog.show();
				mAppsThread = new RecomThread(MainAppsActivity.this, mHandler,
						Constants.RECOM_APP_IS_GAMEONLY, "", mPageNum0,currIndex);
				mAppsThread.start();
			}
		}
	};
	private OnScrollListener mScrollListner1 = new OnScrollListener() {
		private int lastItem = 0;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (mAppAdapter1 != null && lastItem == mAppAdapter1.getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (!mAllowGetLogAgain1)
					return;
				mAllowGetLogAgain1 = false;
				mPageNum1++;

				mProgressDialog = new ProgressDialog(MainAppsActivity.this);
				mProgressDialog.setMessage("加载中，请稍候...");
				mProgressDialog.show();
				mAppsThread = new RecomThread(MainAppsActivity.this, mHandler,
						Constants.RECOM_APP_IS_GAMEONLY, "", mPageNum1,currIndex);
				mAppsThread.start();
			}
		}
	};
	private OnScrollListener mScrollListner2 = new OnScrollListener() {
		private int lastItem = 0;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (mAppAdapter2 != null && lastItem == mAppAdapter2.getCount()
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (!mAllowGetLogAgain2)
					return;
				mAllowGetLogAgain2 = false;
				mPageNum2++;

				mProgressDialog = new ProgressDialog(MainAppsActivity.this);
				mProgressDialog.setMessage("加载中，请稍候...");
				mProgressDialog.show();
				mAppsThread = new RecomThread(MainAppsActivity.this, mHandler,
						Constants.RECOM_APP_IS_GAMEONLY, "", mPageNum2,currIndex);
				mAppsThread.start();
			}
		}
	};
}